package com.atguigu.tingshu.album.receiver;

import com.alibaba.fastjson.JSON;
import com.atguigu.tingshu.album.service.AlbumInfoService;
import com.atguigu.tingshu.album.service.TrackInfoService;
import com.atguigu.tingshu.common.constant.KafkaConstant;
import com.atguigu.tingshu.common.constant.RedisConstant;
import com.atguigu.tingshu.vo.album.TrackStatMqVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Component;

@Component
@Slf4j
public class AlbumReceiver {

    @Autowired
    private TrackInfoService trackInfoService;

    @Autowired
    private RedisTemplate redisTemplate;


    @KafkaListener(topics = KafkaConstant.QUEUE_TRACK_STAT_UPDATE)
    public void updateAlbumStat(ConsumerRecord<String,String> record){
        TrackStatMqVo trackStatMqVo = null;
        try{
            String value = record.value();
            if(value != null){
                trackStatMqVo = JSON.parseObject(value, TrackStatMqVo.class);
                trackInfoService.updateAlbumStat(trackStatMqVo);
                log.info("[专辑服务]，监听到声音统计信息：{}",value);
            }
        }catch (Exception e){
            log.info("[专辑服务]，监听到声音统计信息出现异常，{}",e.getMessage());
            //出现异常需要把之前的分布式锁解开
            if(trackStatMqVo != null){
                String key = RedisConstant.USER_TRACK_REPEAT_STAT_PREFIX + trackStatMqVo.getUserId() + ":" + trackStatMqVo.getTrackId();
                redisTemplate.delete(key);
            }
            throw new RuntimeException();
        }
    }
}
